/**
 *    Copyright 2017-2018 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.econage.eccm.test.base.mybatis.util;

import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.FluentIterable;

import java.util.Collection;
import java.util.List;
import java.util.Map;

public class SqlUtils {


    protected static final Joiner COMMA_JOINER = Joiner.on(",").skipNulls();

    //解析结合类型的参数，转换为合适的占位符字符串，并存入map映射
    public static String formatCollection2ParameterMappings(
            String open, String close,final String item,
            Collection<?> listTypeParameter,
            final Map<String,Object> additionalMap
    ){
        Preconditions.checkNotNull(item,"item is null!");
        if(additionalMap==null){
            throw new NullPointerException(" additional map is null!");
        }

        List<String> parameterTokenList = FluentIterable.from(listTypeParameter).transform(new Function<Object, String>() {
            int count = 0;
            @Override
            public String apply(Object input) {
                String parameterToken = item+StringUtils.UNDERLINE_STR+count;
                count++;
                additionalMap.put(parameterToken,input);
                return "#{"+parameterToken+"}";
            }
        }).toList();

        StringBuilder tokens = new StringBuilder();
        if(StringUtils.isNotEmpty(open)){
            tokens.append(open);
        }
        tokens.append(COMMA_JOINER.join(parameterTokenList));
        if(StringUtils.isNotEmpty(close)){
            tokens.append(close);
        }
        return tokens.toString();
    }


    public static String commaJoin(Collection<String> stringCollection){
        return COMMA_JOINER.join(stringCollection);
    }
    public static String commaJoin(String... stringCollection){
        return COMMA_JOINER.join(stringCollection);
    }
}
